package com.yubiaoqing;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.fileTypes.FileTypes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.psi.impl.file.PsiDirectoryFactory;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.CaseUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author hehb
 * @date 2020/04/03 17:46
 */
public class CreateAction extends AnAction {

    private final String SUFFIX = ".dart";

    @Override
    public void actionPerformed(AnActionEvent e) {
        //获取当前在操作的工程上下文
        Project project = e.getData(PlatformDataKeys.PROJECT);

        // 弹出对话框输入名称
        String name = Messages.showInputDialog(project,
                "Enter a new file name:",
                "New JSON Dart File",
                null);
        if (StringUtils.isBlank(name)) return;
        name = name.trim().toLowerCase();
        //获取当前操作目录或文件
        VirtualFile vf = e.getData(CommonDataKeys.VIRTUAL_FILE);
        // 如果是文件就取他的目录
        if (!vf.isDirectory())
            vf = vf.getParent();
        // 空返回
        if (name.isEmpty()) return;
        // 名字不包括后缀
        String nameWithoutSuffix = name;
        // 如果名字不包含.dart，加上
        if (!name.endsWith(SUFFIX))
            name += SUFFIX;
        else {
            // 去掉后缀
            nameWithoutSuffix = nameWithoutSuffix.replace(SUFFIX, "");
        }
        String template = "";
        // 获取模版内容
        try (InputStream stream = CreateAction.class.getResourceAsStream("/template.dart")) {
            template = IOUtils.toString(stream, "UTF-8");
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        // 创建内存文件
        PsiFile file = PsiFileFactory.getInstance(project)
                .createFileFromText(name,
                        FileTypes.ARCHIVE,
                        template
                                .replaceFirst("template", nameWithoutSuffix)
                                .replaceAll("Template", CaseUtils.toCamelCase(nameWithoutSuffix, true, '_')));
        VirtualFile finalVf = vf;
        String finalName = name;
        ApplicationManager.getApplication().runWriteAction(() -> {
            // 存储到磁盘中
            PsiDirectoryFactory.getInstance(project)
                    .createDirectory(finalVf).add(file);
            VirtualFile f = LocalFileSystem.getInstance()
                    .refreshAndFindFileByIoFile(new File(finalVf.getPath(), finalName));
            // 打开文件
            new OpenFileDescriptor(project, f).navigate(true);
            // flutter pub run build_runner build
            Tools.runBuild(project);
        });

    }

}
